"use strict";
var page = require("webpage").create(),
    args = require('system').args,
    fs = require('fs'),
    siteurl = "http://jxzlxt.jhc.cn/",
    datadir = './data';

page.viewportSize = {width: 1024, height: 800};

var username, password, flow;
if(args.length != 4) {
  console.log('You must provide username, password.');
  phantom.exit();
} else {
  username = args[1];
  password = args[2];
  flow = args[3];
}

var userdir = datadir + '/' + username;
//创建好相应的目录
if(!fs.exists(datadir)) {
  fs.makeDirectory(datadir);
} else if(!fs.exists(userdir)) {
  fs.makeDirectory(userdir);
}

var flow_map = {
  //将所有授课计划保存到本地文件中。
  save_plans: [
    "navigate_to('我的授课计划')",
    "setup_fetch_plans()",
    "phantom_exit()"
  ],
  fill_logs: [
    "navigate_to('填写教学日志')",
    "visit_first_log_item()",
    "fill_log_item()",
    "reset_fill_log_ops()",
    "phantom_exit()"
  ]
};

var current_flow = flow_map[flow];

//输出浏览器的控制台输出，调试时很有帮助。
page.onConsoleMessage = function(msg) {
  console.log('CONSOLE: ' + msg);
};

page.onLoadFinished = function(status) {
  if(status !== 'success') {
    console.log('Unable to open ' + page.url);
    phantom.exit();
  }
  console.log("onLoadFinished: " + page.url);
  //如果是登录页，则直接调用login()
  if(page.url === siteurl) {
    login();
    return;
  }
  //从flow找出下一步操作，并执行
  var next_op = current_flow.shift();
  console.log("next_op: " + next_op);
  eval(next_op);
};

page.open(siteurl);

function login(){
  page.evaluate(function(uname, pass){
    $('#yhlx').val('1');
    $('#yhm').val(uname);
    $('#mm').val(pass);
    $('#btn_dl_c').click();
  }, username, password);
}

//点击指定三级菜单项
function navigate_to(menuitem){
  setTimeout(function(){
    page.evaluate(function(itemname){
      var plan_selector;
      //有多项菜单名为"填写教学日志"，需特殊处理。
      if(itemname === '填写教学日志') {
        plan_selector = '#main-nav > li:nth-child(2) > ul:nth-child(2) > li:nth-child(3) > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)';
      } else {
        plan_selector = '#main-nav ul ul li:contains(' + itemname + ') a';
      }
      $(plan_selector).click();
    }, menuitem);
  }, 1000);
}

//------------------------------导出授课计划------------------------------

//设置抽取所有授课计划的操作顺序，要改变curren_flow数组。
function setup_fetch_plans() {
  setTimeout(function(){
    var myplans = page.evaluate(function(){
      var arr = $('#tabGrid_0 tr[id] td:nth-child(4)')
          .map(function(){
            return $(this).text().trim();
          }).toArray();
      return JSON.stringify(arr);
    });
    console.log('fetched myplans: ' + myplans);
    var plans = JSON.parse(myplans);
    plans.forEach(function(plan){
      var list_op = "list_plan_items('" + plan + "')";
      console.log("unshift list operation: " + list_op);
      current_flow.unshift(list_op);
      var select_op = "select_plan('" + plan + "')";
      console.log("unshift select operation: " + select_op);
      current_flow.unshift(select_op);
      console.log("unshift navigate_to 我的授课计划");
      current_flow.unshift("navigate_to('我的授课计划')");
    });
    page.goBack();
  }, 4000);
}

//根据课程名称(plan_name)进入相应的授课计划详细页面。
function select_plan(plan_name){
  //等xhr请求完成后，才能执行下面的操作。
  setTimeout(function(){
    page.render('select.png');
    page.evaluate(function(pname){
      //plan_name所在行点击checkbox
      $('#tabGrid_0 td[title=' + pname + ']').parent().find('input[type=checkbox]').click();
      $('#btn_skjhsbxq').click();
    }, plan_name);
  }, 5000);
}

//保存授课计划的具体内容。
function list_plan_items(plan_name) {
  var items = page.evaluate(function(){
    var plan_items = [];
    $('th:contains(授课章节与内容)').parent().siblings().each(function(){
      var tds = $(this).find('td');
      var item = {};
      item.attend_date = tds.eq(1).text().trim();
      item.class_section = tds.eq(2).text().trim();
      item.count_of_classes = tds.eq(5).text().trim();
      item.content = tds.eq(6).text().trim();
      plan_items.push(item);
    });
    return JSON.stringify(plan_items);
  });
  fs.write(userdir + '/' + plan_name + '.json', items, 'w');
  //为了触发下一步操作。
  page.goBack();
}

//------------------------------填写教学日志------------------------------

//添加填写日志操作流程时，要将reset_fill_log_ops作为最后操作函数，以便触发下一次的填写操作流程。
function reset_fill_log_ops() {
  current_flow.unshift("reset_fill_log_ops()");
  current_flow.unshift("fill_log_item()");
  current_flow.unshift("visit_first_log_item()");
  current_flow.unshift("navigate_to('填写教学日志')");
  page.open('http://jxzlxt.jhc.cn/xtgl/menu_index.html');
}

function visit_first_log_item() {
  //加载日志数据完成大约需要5秒多的时间。每隔3秒测试日志是否已经取到，最多重试4次。
  var count = 0;
  var interval = setInterval(function(){
    if(count > 4) {
      console.log("Tried too many times. This script will stop." );
      page.render('nolog.png');
      clearInterval(interval);
      //这里是填写教学日志流程的出口。
      phantom.exit();
    }
    count++;
    if(first_log_item_exists()) {
      clearInterval(interval);
      select_first_log_item();
    } else {
      console.log("Cannot find any log items. Try again.");
    }
  }, 3000);
}
//判断是页面中是否有日志
function first_log_item_exists() {
  var flag = false;
  flag = page.evaluate(function(){
    var first_check = $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]');
    console.log("first_check length: " + first_check.length);
    return first_check.length == 1 ? true : false;
  });
//  page.render('check.png');
  return flag;
}

//选择第一条教学日志
function select_first_log_item() {
  page.evaluate(function(){
    $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]').click();
    $('#btn_txjxrz').click();
    //需要等1秒钟左右，会有对话框弹出。
    setTimeout(function(){
      var btn = $('.modal-footer button:nth-child(1)');
      console.log("Button: " + btn.text().trim() + " will be clicked.");
      btn.click();
    },1000);
  });
//  setTimeout(function(){page.render('select_log.png');},1100);
}

//填写教学日志
function fill_log_item() {
  var course_name = page.evaluate(function(){
    return $('#rows_1_1_td label').text().trim();
  });
  console.log("course_name: " + course_name);
  if(course_name === undefined || course_name === ''){
    page.render('no_course_name.png');
    phantom_exit();
  }
  var plans = fs.read(userdir + '/' + course_name + '.json');
  page.evaluate(function(page_plans){
    var pattern = /.*(\d{1,2}-\d{1,2}).*/;
    var course_date = $('#rows_5_1_td label').text().trim();
    var course_time = $('#rows_1_2_td label').text().trim();
    var cname = $('#rows_1_1_td label').text().trim();
    console.log("course_date: " + course_date + ", course_time: " + course_time);
    //从"星期四[7-8节]"中抽取出"7-8"
    var num_str = pattern.exec(course_time)[1];
    if(!num_str) {
      console.log("Cannot extract num_str from course_time: " + course_time);
      return;
    }
    var page_plan_items = JSON.parse(page_plans);
    var item = page_plan_items.filter(function(it){
      return it.attend_date === course_date
        && it.class_section.indexOf(num_str) != -1;
    });
    var fill_content;
    if(item.length != 1){
      console.log("Find " + item.length + " matched items in plans data.");
      console.log("Cannot find unique log item for num_str: " + num_str);
      //软件设计项目实践的日期与授课计划上无法一致。
      if(cname === '软件设计项目实践' || cname === '移动APP实训（Android）') {
        console.log("软件设计项目实践与授课计划时间不一致,或者没有授课计划的课时。");
        fill_content = '实践指导';
      } else {
        return;
      }
    } else {
      fill_content = item[0].content;
      console.log("logitem content: " + fill_content);
    }
    //填入日志
    $('#SKNR_3').val(fill_content);
    //点击保存按钮
    $('.form-actions button:nth-child(1)').click();
    //弹出对话框中点击确定
    setTimeout(function(){
      $('.modal-footer button:nth-child(2)').click();
    }, 200);
  }, plans);
//  page.render('fill.png');
}

function phantom_exit(){
  page.close();
  setTimeout(function(){
    phantom.exit();
  },100);
}
